package net.lovesrc.allin.biz.ercx;

import com.alibaba.fastjson.JSONObject;
import com.zhouzhou.fastjava.http.MyHttpRequest;
import com.zhouzhou.fastjava.http.Requests;
import net.lovesrc.allin.biz.BaseService;
import net.lovesrc.allin.utils.ImageUtils;
import net.lovesrc.allin.utils.MyRandomUtils;
import net.lovesrc.support.service.mobileverifycode.MobileVerifyCodeService;
import net.lovesrc.support.service.mobileverifycode.MobileVerifyCodeWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Arrays;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class ErcxRegisterService extends BaseService {

    @Autowired
    private MobileVerifyCodeService noNameMobileVerifyCodeService;

    public String newRegister() {

        String prefix = "86";

        String mobile;
        try {
            mobile = doGetNewMobile(null);
        } catch (Exception e) {
            try {
                TimeUnit.SECONDS.sleep(6);
            } catch (InterruptedException ex) {

            }
            throw e;
        }


        Requests.get("https://api.ercx.me/uc/captcha/mm/phone")
                .param("phone", prefix + mobile)
                .execute().asJson();

        String verifyCode = getMobileVerifyCodeWrapper().getVerifyCodeFromPhone(mobile, 4);

        String password = MyRandomUtils.randomComplexPassword();

        String uid = getUId();
        JSONObject jsonObject = Requests.post("https://api.ercx.me/uc/register/phone")
                .header("check", "phone:" + prefix + mobile + ":" + verifyCode)
                .contentType("application/json")
                .param("country", "China")
                .param("inviteCode", "U00002574OL")
                .param("mobilePhone", prefix + mobile)
                .param("password", password)
                .param("promotion", null)
                .param("terminal", "android")
                .param("tid", uid)
                .param("username", "")
                .execute().asJson();

        if (jsonObject == null || !"200".equals(jsonObject.getString("code"))) {
            return "";
        }

        JSONObject tgcJsonObject = Requests.post("https://www.ercx.me/cas/v1/tickets")
                .contentType("application/x-www-form-urlencoded")
                .header("tid", uid)
                .param("username", mobile)
                .param("password", password)
                .param("rememberMe", true)
                .execute().asJson();

        Object tgc = tgcJsonObject.get("tgc");
        String phone = doGetNewMobile(mobile);

        //验证码发送
        Requests.get("https://www.ercx.me/cas/captcha/permission")
                .param("type", "phone")
                .header("tgt", tgc)
                .execute().asJson();

        String loginVerifyCode = getMobileVerifyCodeWrapper().getVerifyCodeFromPhone(phone, 4);

        Requests.get("https://www.ercx.me/cas/captcha/check")
                .header("check", "phone::" + loginVerifyCode)
                .header("tgt", tgc)
                .execute().asJson();


        String st = Requests.post("https://www.ercx.me/cas/v1/tickets/" + tgc)
                .contentType("application/x-www-form-urlencoded")
                .header("tid", uid)
                .header("tgt", tgc)
                .param("service", "https://api.ercx.me/ac/cas?client_name=CasClient")
                .execute().asText();

        //login
        BasicCookieStore basicCookieStore = new BasicCookieStore();
        Cookie basicClientCookie1 = new BasicClientCookie2("acsid", getUId());
        Cookie basicClientCookie2 = new BasicClientCookie2("minesid", getUId());
        Cookie basicClientCookie3 = new BasicClientCookie2("otcsid", getUId());
        Cookie basicClientCookie4 = new BasicClientCookie2("spotsid", getUId());
        Cookie basicClientCookie5 = new BasicClientCookie2("ucsid", getUId());
        Cookie basicClientCookie6 = new BasicClientCookie2("otc-proxy-apisid", getUId());

        basicCookieStore.addCookies(new Cookie[]{basicClientCookie1, basicClientCookie2, basicClientCookie3, basicClientCookie4, basicClientCookie5, basicClientCookie6});
        HttpClient httpClient = Requests.newHttpClient(basicCookieStore);
        MyHttpRequest.get(httpClient, "https://api.ercx.me/ac/cas")
                .header("tid", uid)
                .header("tgt", tgc)
                .param("ticket", st)
                .execute().asText();


        String direct = "D:\\左友洋";

        File file = new File(direct);
        File[] files = file.listFiles();
        Optional<File> first = Arrays.stream(files).filter(file1 -> file1.getName().contains("信息.txt"))
                .findFirst();
        if (!first.isPresent()) {
            return "";
        }
        String value = ImageUtils.getValue(first.get());
        String identityNo = StringUtils.substringAfter(value, "----");
        //身份证验证
        MyHttpRequest.get(httpClient, "https://api.ercx.me/uc/realname/check/identity")
                .header("tid", uid)
                .header("tgt", tgc)
                .param("identityNo", identityNo)
                .execute().asText();


        //图片上传
        Arrays.stream(files).filter(file1 -> !file1.getName().contains("信息.txt")).forEach(file1 -> {
            MyHttpRequest.get(httpClient, "https://api.ercx.me/uc/upload/oss/base64")
                    .contentType("application/json")
                    .header("tid", uid)
                    .header("tgt", tgc)
                    .param("base64Data", ImageUtils.GetImageStr(file1))
                    .param("oss", "False")
                    .execute().asText();
        });

        return "";
    }

    public void sign(){

        String mobile = "19528002013";
        String password = "Dq18633886";
        String uid = getUId();
        JSONObject tgcJsonObject = Requests.post("https://www.ercx.me/cas/v1/tickets")
                .contentType("application/x-www-form-urlencoded")
                .header("tid", uid)
                .param("username", mobile)
                .param("password", password)
                .param("rememberMe", true)
                .execute().asJson();

        Object tgc = tgcJsonObject.get("tgc");
        String phone = doGetNewMobile(mobile);

        //验证码发送
        Requests.get("https://www.ercx.me/cas/captcha/permission")
                .param("type", "phone")
                .header("tgt", tgc)
                .execute().asJson();

        String loginVerifyCode = getMobileVerifyCodeWrapper().getVerifyCodeFromPhone(phone, 4);

        Requests.get("https://www.ercx.me/cas/captcha/check")
                .header("check", "phone::" + loginVerifyCode)
                .header("tgt", tgc)
                .execute().asJson();


        String st = Requests.post("https://www.ercx.me/cas/v1/tickets/" + tgc)
                .contentType("application/x-www-form-urlencoded")
                .header("tid", uid)
                .header("tgt", tgc)
                .param("service", "https://api.ercx.me/ac/cas?client_name=CasClient")
                .execute().asText();

        //login
        BasicCookieStore basicCookieStore = new BasicCookieStore();
        Cookie basicClientCookie1 = new BasicClientCookie2("acsid", getUId());
        Cookie basicClientCookie2 = new BasicClientCookie2("minesid", getUId());
        Cookie basicClientCookie3 = new BasicClientCookie2("otcsid", getUId());
        Cookie basicClientCookie4 = new BasicClientCookie2("spotsid", getUId());
        Cookie basicClientCookie5 = new BasicClientCookie2("ucsid", getUId());
        Cookie basicClientCookie6 = new BasicClientCookie2("otc-proxy-apisid", getUId());

        basicCookieStore.addCookies(new Cookie[]{basicClientCookie1, basicClientCookie2, basicClientCookie3, basicClientCookie4, basicClientCookie5, basicClientCookie6});
        HttpClient httpClient = Requests.newHttpClient(basicCookieStore);
        MyHttpRequest.get(httpClient, "https://api.ercx.me/ac/cas")
                .header("tid", uid)
                .header("tgt", tgc)
                .param("ticket", st)
                .execute().asText();


        String direct = "D:\\左友洋";

        File file = new File(direct);
        File[] files = file.listFiles();
        Optional<File> first = Arrays.stream(files).filter(file1 -> file1.getName().contains("信息.txt"))
                .findFirst();
        if (!first.isPresent()) {
            return ;
        }
        String value = ImageUtils.getValue(first.get());
        String identityNo = StringUtils.substringAfter(value, "----");
        //身份证验证
        MyHttpRequest.get(httpClient, "https://api.ercx.me/uc/realname/check/identity")
                .header("tid", uid)
                .header("tgt", tgc)
                .param("identityNo", identityNo)
                .execute().asText();


        //图片上传
        Arrays.stream(files).filter(file1 -> !file1.getName().contains("信息.txt")).forEach(file1 -> {
            MyHttpRequest.post(httpClient, "https://api.ercx.me/uc/upload/oss/base64")
                    .contentType("application/json")
                    .header("tid", uid)
                    .header("tgt", tgc)
                    .param("base64Data", ImageUtils.GetImageStr(file1))
                    .param("oss", "False")
                    .execute().asText();
        });

    }

    private String doGetNewMobile(String phone) {
        for (; ; ) {
            String mobile = getMobileVerifyCodeWrapper().getPhone(phone);
//            if (jdbcTemplate.queryForObject("select count(1) from ERCX_USER_INFO where username = ?", long.class, mobile) > 0) {
//                getMobileVerifyCodeWrapper().addBlack(mobile);
//                continue;
//            }
            return mobile;
        }
    }

    private MobileVerifyCodeWrapper getMobileVerifyCodeWrapper() {
        return new MobileVerifyCodeWrapper(noNameMobileVerifyCodeService, "15512");
    }


    private static String getUId() {
        String guid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
        Matcher matcher = pattern.matcher(guid);
        while (matcher.find()) {
            String group = matcher.group();
            int r = (int) Math.ceil(Math.random() * 16);
            int v = "x".equals(group) ? r : (r & 0x3 | 0x8);
            guid = guid.replaceFirst(group, Integer.toHexString(v));
        }
        return guid;
    }

    static Pattern pattern = Pattern.compile("[xy]");

    public static void main(String[] args) {


    }
}
